package com.tx.spring_security.spring_security_demo.config;

import com.tx.spring_security.spring_security_demo.service.UserDetailImpl;
import com.tx.spring_security.spring_security_demo.util.MercuryEncoder;
import com.tx.spring_security.spring_security_demo.util.MercuryPasswordEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author ：tx
 * @description：
 * @modified By：
 * @version:
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true) //spring security默认是关闭注解的，该注解的作用是开启注解
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    UserDetailImpl userDetailsService;

    /**
     * @author tx
     * @description  在内存中创建用户名，密码和角色
     * @param  * @Param: auth
     * @return void
    **/
   @Autowired
    public void configGlobal(AuthenticationManagerBuilder auth) throws Exception {
      /* auth
               .inMemoryAuthentication()
               .passwordEncoder(new MercuryEncoder())
               .withUser("admin").password("111111").roles("ADMIN");

       auth.inMemoryAuthentication().withUser("mercury").password("111111").roles("USER");

       auth.inMemoryAuthentication().passwordEncoder(new MercuryEncoder()).withUser("stt").password("111111").roles("USER");
*/
        auth.userDetailsService(userDetailsService).passwordEncoder(new MercuryPasswordEncoder());

   }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        //请求授权！
        http.authorizeRequests().antMatchers("/admin/showAdmin").hasRole("ADMIN");
        http.authorizeRequests().antMatchers("/user/findUserMessage").access("hasRole('ADMIN') or hasRole('USER')");


        //指定登录界面为login请求
       http
          /* .authorizeRequests() .anyRequest().authenticated()
           .and()*/
           .formLogin().loginPage("/login").loginProcessingUrl("/login/form").permitAll();


       //注销
        http.logout().logoutUrl("/mercury/logout").logoutSuccessUrl("/mercury/index")
                .logoutSuccessHandler(new LogoutSuccessHandler() {
                    @Override
                    public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
                        System.out.println("进入了logoutSuccessHandler（），退出成功了，并且logoutSuccessUrl()无效了");
                    }
                })
                .invalidateHttpSession(true)
                .addLogoutHandler(new LogoutHandler() {
                    @Override
                    public void logout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) {
                        System.out.println("进入了logoutHandler()");
                    }
                })
                .deleteCookies()
                .permitAll();



        super.configure(http);
    }
}
